package demo.screens
{
	import com.cheezeworld.screens.IScreenItem;
	import com.cheezeworld.screens.Root;
	import com.cheezeworld.utils.Input;
	import com.urbansquall.ginger.Animation;
	import com.urbansquall.ginger.AnimationPlayer;
	import com.urbansquall.ginger.events.AnimationEvent;
	import com.urbansquall.ginger.tools.AnimationBuilder;
	import com.urbansquall.ginger.tools.AnimationPlayerFactory;
	import com.urbansquall.ui.CustomTextField;
	
	import demo.BitmapDataLibrary;
	
	import flash.display.BitmapData;
	

	public class FactoryDemo extends DemoScreen
	{
		public function FactoryDemo(a_parentScreen:IScreenItem=null)
		{
			super(a_parentScreen);
			
			screenLabel = "Animation Factory";
			
			registerBomb();
			
			var txt:CustomTextField = new CustomTextField( "( Click to spawn a bomb! )", 0x0, 18 );
			txt.x = Root.WIDTH/2 - txt.width / 2;
			txt.y = 50;
			addChild( txt );	
		}
		
		public override function update(a_timePassed:int):void
		{
			if( Input.instance.isMousePressed && Input.instance.mouseY < Root.HEIGHT - 40 )
			{
				var bomb:AnimationPlayer = m_animationFactory.instantiate( "bomb" );
				bomb.x = Input.instance.mouseX;
				bomb.y = Input.instance.mouseY;
				addChild( bomb );
				bomb.startSelfTick( 30 );
				bomb.queue( "die" );
				bomb.addEventListener( AnimationEvent.CHANGE, onAnimationEvent );
			}
		}
		
		// -- PRIVATE --
		
		private function onAnimationEvent( e:AnimationEvent ) : void
		{
			if( e.animationID == "die" && e.begin == false )
			{
				AnimationPlayer( e.currentTarget ).removeEventListener( AnimationEvent.CHANGE, onAnimationEvent );
				removeChild( e.currentTarget as AnimationPlayer );
			}
		}
		
		private function registerBomb() : void
		{
			var bomb:AnimationPlayer;
			var bdLib:BitmapDataLibrary = new BitmapDataLibrary();
			var bd:BitmapData = bdLib.lookupBitmapData( BitmapDataLibrary.BOMB_TS );
			
			// Create bomb idle animation
			var animation:Animation = AnimationBuilder.importStrip( 24, bd, 16, 16, 4, 0, 0, 120, -8, -8 );			
			bomb = new AnimationPlayer();
			bomb.addAnimation( "idle", animation );
			
			// Create exploding animation
			animation = AnimationBuilder.importStrip( 24, bd, 32, 32, 4, 0, 16, 120, -16, -16 );
			bomb.addAnimation( "die", animation );
			
			m_animationFactory = new AnimationPlayerFactory();
			m_animationFactory.register( "bomb", bomb );
		}
		
		private var m_animationFactory:AnimationPlayerFactory
		
	}
}